//
//  UTTaskRecorderCell.swift
//  UniversalTool
//
//  Created by LGB on 2025/3/4.
//

import UIKit

class UTTaskRecorderCell: UITableViewCell {

    @IBOutlet weak var contentLeft: NSLayoutConstraint!
    
    @IBOutlet weak var containerContentView: UIView!
    @IBOutlet weak var taskName: UILabel!
    @IBOutlet weak var note: UILabel!
    @IBOutlet weak var collection: UICollectionView!
    @IBOutlet weak var collectionHeight: NSLayoutConstraint!
    @IBOutlet weak var delete: UIButton!
    @IBOutlet weak var deleteWidth: NSLayoutConstraint!
    
    let cellIdentifier = "UTTaskRecorderStatusCell"
    
    var reloadData:(() -> Void)?
    var model: UTTaskCounterItemModel? {
        didSet {
            guard let model = model else { return }
            taskName.text = (model.isRepeat ? "重复任务：去" : "任务：去") + "\(model.number)次" + model.taskName
            note.text = "备注：" + (model.note.isEmpty ? "暂无" : model.note)
            collection.reloadData()
            collectionHeight.constant = self.collection.collectionViewLayout.collectionViewContentSize.height
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(_:)))
        swipeLeft.direction = .left
        containerContentView.addGestureRecognizer(swipeLeft)
        
        let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(_:)))
        swipeRight.direction = .right
        containerContentView.addGestureRecognizer(swipeRight)
        let flowLayout =  UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: 24, height: 24)
        flowLayout.minimumInteritemSpacing = (self.collection.frame.size.width - 24 * 5) / 4
        flowLayout.minimumLineSpacing = 25
        self.collection.collectionViewLayout = flowLayout
        self.collection.showsVerticalScrollIndicator = false
        self.collection.delegate = self
        self.collection.dataSource = self
        self.collection.register(UINib(nibName: cellIdentifier, bundle: nil), forCellWithReuseIdentifier: cellIdentifier)
    }
    
    @objc func handleSwipe(_ sender: UISwipeGestureRecognizer) {
        switch sender.direction {
        case .left:
            self.contentLeft.constant = -40
            self.delete.isHidden = false
            self.deleteWidth.constant = 40
        case .right:
            self.contentLeft.constant = 15
            self.delete.isHidden = true
            self.deleteWidth.constant = 0
        default:
            break
        }
        
    }
    
    @IBAction func didDelete(_ sender: UIButton) {
        if let model = model, let data = UTTaskCounterHelper.taskCounterInfo() {
            data.datas.removeAll { $0.no == model.no }
            UTTaskCounterHelper.dc_saveTaskCounterInfo(taskCounter: data)
        }
        if let handler = reloadData {
            handler()
        }
    }
    
}

extension UTTaskRecorderCell: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        guard let model = model else { return 0 }
        return model.programmeList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as? UTTaskRecorderStatusCell else {
            fatalError("Unable to dequeue cell")
        }
        if let model = model {
            cell.model = model.programmeList[indexPath.row]
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let model = model {
            if indexPath.row > 0 {
                let previousItem = model.programmeList[indexPath.row - 1]
                if !previousItem.isFinish {
                    UIApplication.shared.keyWindow?.makeToast("请完成前面任务", position: .center)
                    return
                }
            }
            let item = model.programmeList[indexPath.row]
            if item.isFinish { return }
            item.isFinish = !item.isFinish
            if model.programmeList.allSatisfy({ $0.isFinish }) {
                model.isFinish = true
                let currentDate = Date()
                let formatter = DateFormatter()
                formatter.dateFormat = "yyyy-MM-dd HH:mm"
                formatter.locale = Locale(identifier: "zh_CN")
                let formattedDate = formatter.string(from: currentDate)
                model.finishTime = formattedDate
                UIApplication.shared.keyWindow?.makeToast("已完成当前任务", position: .center)
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                    if let data = UTTaskCounterHelper.taskCounterInfo() {
                        data.datas.forEach { item in
                            if item.no == model.no {
                                item.isFinish = model.isFinish
                                item.finishTime = model.finishTime
                                item.programmeList = model.programmeList
                            }
                        }
                        if model.programmeList.allSatisfy({ $0.isFinish }) {
                            if model.isRepeat {
                                let itemModel = UTTaskCounterItemModel()
                                itemModel.no = data.datas.count
                                itemModel.taskName = model.taskName
                                itemModel.number = model.number
                                for _ in 1...model.number {
                                    let item = UTTaskCounterFinishModel()
                                    itemModel.programmeList.append(item)
                                }
                                itemModel.note = model.note
                                itemModel.isRepeat = model.isRepeat
                                data.datas.append(itemModel)
                            }
                        }
                        UTTaskCounterHelper.dc_saveTaskCounterInfo(taskCounter: data)
                    }
                    
                    if let handler = self.reloadData {
                        handler()
                    }
                }
                
                return
            }
            if let data = UTTaskCounterHelper.taskCounterInfo() {
                data.datas.forEach { item in
                    if item.no == model.no {
                        item.isFinish = model.isFinish
                        item.finishTime = model.finishTime
                        item.programmeList = model.programmeList
                    }
                }
                if model.programmeList.allSatisfy({ $0.isFinish }) {
                    if model.isRepeat {
                        let itemModel = UTTaskCounterItemModel()
                        itemModel.no = data.datas.count
                        itemModel.taskName = model.taskName
                        itemModel.number = model.number
                        for _ in 1...model.number {
                            let item = UTTaskCounterFinishModel()
                            itemModel.programmeList.append(item)
                        }
                        itemModel.note = model.note
                        itemModel.isRepeat = model.isRepeat
                        data.datas.append(itemModel)
                    }
                }
                UTTaskCounterHelper.dc_saveTaskCounterInfo(taskCounter: data)
            }
            
            if let handler = reloadData {
                handler()
            }
        }
    }
    
}
